﻿//using Mapster;
//using Microsoft.AspNetCore.Mvc;
//using RazorEngine;
//using RazorEngine.Templating;
//using RuoVea.ExApp;
//using RuoVea.ExEnum;
//using RuoVea.ExUtil.EnumExtension;
//using RuoVea.ExUtil.Exceptions;
//using SqlSugar;
//using System;
//using System.Collections.Generic;
//using System.IO;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using Ylztdy.DbFacte;
//using YlzTdy.EasyRis.Server;
//using YlzTdy.Utiliy;
//using RuoVea.ExUtil;
//using System.Reflection;
//using RuoVea.ExIdGen;

//namespace YlzTdy.RisApi.Controllers
//{
//    /// <summary>
//    /// 数据库管理
//    /// </summary>
//    [ApiController]
//    [Route("DataBase")]
//    public class DataBaseManagerController : ApiBaseController
//    {
//        public readonly RisContext _risContext;

//        /// <summary>
//        /// 
//        /// </summary>
//        /// <param name="risContext"></param>
//        public DataBaseManagerController(RisContext risContext) {
//            _risContext = risContext;
//        }

//        /// <summary>
//        /// 获取所有表
//        /// </summary>
//        /// <returns></returns>
//        [HttpGet("/dataBase/tableInfoList")]
//        public List<DbTableInfo> GetTableInfoList()
//        {
//            return _risContext.DB.DbMaintenance.GetTableInfoList(false).OrderBy(x=>x.Name).ToList();
//        }
//        /// <summary>
//        /// 创建模型
//        /// </summary>
//        /// <param name="input"></param>
//        /// <exception cref="ParamiterException"></exception>
//        [HttpPost("/table/createEntity")]
//        public void CreateEntity(CreateEntityInput input)
//        {
//            input.Position = string.IsNullOrWhiteSpace(input.Position) ? "YlzTdy.Application" : input.Position;

//            //if(input.EntityName.IsNullOrWhiteSpace())
//            input.EntityName =RuoVea.ExUtil.ExString.Str.ToCamelAny( input.TableName);

         
//            var templatePath = GetTemplatePath("Entity.cs.vm");
           
//            DbTableInfo dbTableInfo =  _risContext.DB.DbMaintenance.GetTableInfoList(false).FirstOrDefault(m => m.Name == input.TableName);
//            if (dbTableInfo == null)
//                throw new ParamiterException(ErrorCode.db1001.GetEnumText());

//            List<DbColumnInfo> dbColumnInfos =  _risContext.DB.DbMaintenance.GetColumnInfosByTableName(input.TableName, false);

//            dbColumnInfos.ForEach(m =>
//            {
//                m.DataType = CodeGenUtil.ConvertDataType(m.DataType);
//            });
//            var tContent =System.IO. File.ReadAllText(templatePath);

//            List<DbColumnInfo> dbColumnInfo = new List<DbColumnInfo>();
//            if (input.BaseClassName.NotNullOrWhiteSpace() && ("DBEntityBase"== input.BaseClassName || "DBEntityTenantBase" == input.BaseClassName))
//            {
//                List<string> lstr = new List<string> {
//                "CreateTime",
//                "CreatedUserId",
//                "EditeTime",
//                "EditorUserId",
//                "Deleted",
//                "CreatedUserName",
//                "EditorUserName"
//                };
//                dbColumnInfo = dbColumnInfos.Where(x=> !lstr.Contains(x.DbColumnName)).ToList();
//            }

//            input.BaseClassName = string.IsNullOrWhiteSpace(input.BaseClassName) ? "" : $" : {input.BaseClassName}";

//            var tttdata = new
//            {
//                input.TableName,
//                input.EntityName,
//                input.BaseClassName,
//                Description = dbTableInfo.Description,
//                TableField = dbColumnInfo
//           };

//            var tResult = Engine.Razor.RunCompile(tContent, RuoVea.ExCrypt.Md5Crypt.Encrypt(tContent), null, tttdata);

//            var targetPath = GetTargetPath(input,"","",   "Entity");

//            System.IO.File.WriteAllText(targetPath, tResult, System.Text.Encoding.UTF8);
//        }

//        /// <summary>
//        /// 
//        /// </summary>
//        /// <param name="input"></param>
//        [HttpPost("/table/createServer")]
//        public void CreateServerApi(CreateEntityInput input) {
//            CreateInput(input);
//            CreateIserver(input);
//            CreateServer(input);
//            CreateControler(input);
//            SqlBuild(input);
//        }

//        private void CreateInput(CreateEntityInput input) {
//            input.Position = string.IsNullOrWhiteSpace(input.Position) ? "YlzTdy.Application" : input.Position;

//            if (input.EntityName.IsNullOrWhiteSpace())
//                input.EntityName = RuoVea.ExUtil.ExString.Str.ToCamelAny(input.TableName);


//            var templatePath = GetTemplatePath("Input.cs.vm");

//            DbTableInfo dbTableInfo = _risContext.DB.DbMaintenance.GetTableInfoList(false).FirstOrDefault(m => m.Name == input.TableName);
//            if (dbTableInfo == null)
//                throw new ParamiterException(ErrorCode.db1001.GetEnumText());

//            if(dbTableInfo.Description.IsNullOrWhiteSpace())
//                throw new ParamiterException("表备注不存在");

//            List<DbColumnInfo> dbColumnInfos = _risContext.DB.DbMaintenance.GetColumnInfosByTableName(input.TableName, false);

//            dbColumnInfos.ForEach(m =>
//            {
//                m.DataType = CodeGenUtil.ConvertDataType(m.DataType);
//            });
//            var tContent = System.IO.File.ReadAllText(templatePath);

//            List<DbColumnInfo> dbColumnInfo = new List<DbColumnInfo>();
//            //if (input.BaseClassName.NotNullOrWhiteSpace() && ("DBEntityBase" == input.BaseClassName || "DBEntityTenantBase" == input.BaseClassName))
//            {
//                List<string> lstr = new List<string> {
//                "CreateTime",
//                "CreatedUserId",
//                "EditeTime",
//                "EditorUserId",
//                "Deleted",
//                "CreatedUserName",
//                "EditorUserName",
//                "TenantId"
//                };
//                dbColumnInfo = dbColumnInfos.Where(x => !lstr.Contains(x.DbColumnName)).ToList();
//            }

//            input.BaseClassName = string.IsNullOrWhiteSpace(input.BaseClassName) ? "" : $" : {input.BaseClassName}";

//            var tttdata = new
//            {
//                ClassName=  input.EntityName,
//                BusName = dbTableInfo.Description,
//                TableField = dbColumnInfo
//            };

//            var tResult = Engine.Razor.RunCompile(tContent, RuoVea.ExCrypt.Md5Crypt.Encrypt(tContent), null, tttdata);

//            var targetPath = GetTargetPath(input,"", "Input", "Server", input.EntityName,"Dto");


//            System.IO.File.WriteAllText(targetPath, tResult, System.Text.Encoding.UTF8);

//        }

//        private void CreateIserver(CreateEntityInput input) {
//            input.Position = string.IsNullOrWhiteSpace(input.Position) ? "YlzTdy.Application" : input.Position;
//            input.EntityName = RuoVea.ExUtil.ExString.Str.ToCamelAny(input.TableName);
//            var templatePath = GetTemplatePath("IServer.cs.vm");
//            var tContent = System.IO.File.ReadAllText(templatePath);

//            DbTableInfo dbTableInfo = _risContext.DB.DbMaintenance.GetTableInfoList(false).FirstOrDefault(m => m.Name == input.TableName);
//            if (dbTableInfo == null)
//                throw new ParamiterException(ErrorCode.db1001.GetEnumText());

//            var tttdata = new
//            {
//                ClassName = input.EntityName,
//                BusName = dbTableInfo.Description,
//            };

//            var tResult = Engine.Razor.RunCompile(tContent, RuoVea.ExCrypt.Md5Crypt.Encrypt(tContent), null, tttdata);
//            var targetPath = GetTargetPath(input,prifix:"I", lastfix: "Service", "Server", input.EntityName);
//            System.IO.File.WriteAllText(targetPath, tResult, System.Text.Encoding.UTF8);

//        }

//        private void CreateServer(CreateEntityInput input) {
//            input.Position = string.IsNullOrWhiteSpace(input.Position) ? "YlzTdy.Application" : input.Position;
//            input.EntityName = RuoVea.ExUtil.ExString.Str.ToCamelAny(input.TableName);
//            var templatePath = GetTemplatePath("Server.cs.vm");
//            var tContent = System.IO.File.ReadAllText(templatePath);

//            DbTableInfo dbTableInfo = _risContext.DB.DbMaintenance.GetTableInfoList(false).FirstOrDefault(m => m.Name == input.TableName);
//            if (dbTableInfo == null)
//                throw new ParamiterException(ErrorCode.db1001.GetEnumText());

//            var tttdata = new
//            {
//                ClassName = input.EntityName,
//                BusName = dbTableInfo.Description,
//            };

//            var tResult = Engine.Razor.RunCompile(tContent, RuoVea.ExCrypt.Md5Crypt.Encrypt(tContent), null, tttdata);
//            var targetPath = GetTargetPath(input,prifix:"",lastfix: "Service",  "Server", input.EntityName);
//            System.IO.File.WriteAllText(targetPath, tResult, System.Text.Encoding.UTF8);
//        }

//        private void CreateControler(CreateEntityInput input) {
//            input.Position = string.IsNullOrWhiteSpace(input.Position) ? "YlzTdy.Application" : input.Position;
//                input.EntityName = RuoVea.ExUtil.ExString.Str.ToCamelAny(input.TableName);
//            var templatePath = GetTemplatePath("Controler.cs.vm");
//            var tContent = System.IO.File.ReadAllText(templatePath);

//            DbTableInfo dbTableInfo = _risContext.DB.DbMaintenance.GetTableInfoList(false).FirstOrDefault(m => m.Name == input.TableName);
//            if (dbTableInfo == null)
//                throw new ParamiterException(ErrorCode.db1001.GetEnumText());

//            var tttdata = new
//            {
//                ClassName=  input.EntityName,
//                BusName = dbTableInfo.Description,
//            };

//            var tResult = Engine.Razor.RunCompile(tContent, RuoVea.ExCrypt.Md5Crypt.Encrypt(tContent), null, tttdata);
//            var targetPath = GetTargetPath(input,"",lastfix: "Controller",path: "Controller");
//            System.IO.File.WriteAllText(targetPath, tResult, System.Text.Encoding.UTF8);
//        }

//        private void SqlBuild(CreateEntityInput input)
//        {
//            input.Position = string.IsNullOrWhiteSpace(input.Position) ? "YlzTdy.Application" : input.Position;
//            input.EntityName = RuoVea.ExUtil.ExString.Str.ToCamelAny(input.TableName);
//            var templatePath = GetTemplatePath("IServer.cs.vm");
//            var tContent = System.IO.File.ReadAllText(templatePath);

//            DbTableInfo dbTableInfo = _risContext.DB.DbMaintenance.GetTableInfoList(false).FirstOrDefault(m => m.Name == input.TableName);
//            if (dbTableInfo == null)
//                throw new ParamiterException(ErrorCode.db1001.GetEnumText());

//            long Id = IdGenerator.Id;
//            long rootId = 142307070912345;
//            string pathRoot = "system";
//            input.EntityName= input.EntityName.ToLower();
//            string urlName = input.TableName.ToLower();

//            StringBuilder sql = new StringBuilder();
//            sql.AppendLine("-- 菜单数据插入sql语句");
//            sql.Append("INSERT INTO [dbo].[sys_menu] ([Id], [Pid], [Pids], [Name], [Code], [Type], [Icon], [Router], [Component], [Permission], [Application], [OpenType], [Visible], [Link], [Redirect], [Weight], [Sort], [Remark], [Status], [CreateTime], [EditeTime], [CreatedUserId], [CreatedUserName], [EditorUserId], [EditorUserName], [Deleted]) ");
//            sql.Append("VALUES ("+ Id + ", "+ rootId + ", N'[0],["+ rootId + "],', N'"+ dbTableInfo.Description+ "管理', N'"+ urlName + "', 1, N'', N'', N'/view/"+ pathRoot + "/"+ input.EntityName + "/index.vue', N'', N'system', 0, N'Y', N'', N'', 1, 1000, N'', 0, '2023-01-01 00:01:01.001', NULL, 142307070910551, N'superAdmin', 0, NULL, '0');");
//            sql.AppendLine();
//            sql.AppendLine("-- 查询权限");
//            sql.Append("INSERT INTO [dbo].[sys_menu] ([Id], [Pid], [Pids], [Name], [Code], [Type], [Icon], [Router], [Component], [Permission], [Application], [OpenType], [Visible], [Link], [Redirect], [Weight], [Sort], [Remark], [Status], [CreateTime], [EditeTime], [CreatedUserId], [CreatedUserName], [EditorUserId], [EditorUserName], [Deleted]) ");
//            sql.Append("VALUES ("+IdGenerator.Id+", "+ Id + ", N'["+ rootId + "],["+ Id + "],', N'" + dbTableInfo.Description + "查询', N'" + urlName + "_page', 2, N'', N'', N'', N'"+ input.EntityName + ":page', N'system', 0, N'Y', N'', N'', 1, 10, N'', 0, '2023-01-01 00:01:01.001', NULL, 142307070910551, N'superAdmin', 0, NULL, '0');");
//            sql.AppendLine();
//            sql.AppendLine("-- 增加权限");
//            sql.Append("INSERT INTO [dbo].[sys_menu] ([Id], [Pid], [Pids], [Name], [Code], [Type], [Icon], [Router], [Component], [Permission], [Application], [OpenType], [Visible], [Link], [Redirect], [Weight], [Sort], [Remark], [Status], [CreateTime], [EditeTime], [CreatedUserId], [CreatedUserName], [EditorUserId], [EditorUserName], [Deleted]) ");
//            sql.Append("VALUES (" + IdGenerator.Id + ", " + Id + ", N'[" + rootId + "],[" + Id + "],', N'" + dbTableInfo.Description + "增加', N'" + urlName + "_add', 2, N'', N'', N'', N'" + input.EntityName + ":add', N'system', 0, N'Y', N'', N'', 1, 20, N'', 0, '2023-01-01 00:01:01.001', NULL, 142307070910551, N'superAdmin', 0, NULL, '0');");
//            sql.AppendLine();
//            sql.AppendLine("-- 编辑权限");
//            sql.Append("INSERT INTO [dbo].[sys_menu] ([Id], [Pid], [Pids], [Name], [Code], [Type], [Icon], [Router], [Component], [Permission], [Application], [OpenType], [Visible], [Link], [Redirect], [Weight], [Sort], [Remark], [Status], [CreateTime], [EditeTime], [CreatedUserId], [CreatedUserName], [EditorUserId], [EditorUserName], [Deleted]) ");
//            sql.Append("VALUES (" + IdGenerator.Id + ", " + Id + ", N'[" + rootId + "],[" + Id + "],', N'" + dbTableInfo.Description + "编辑', N'" + urlName + "_edit', 2, N'', N'', N'', N'" + input.EntityName + ":edit', N'system', 0, N'Y', N'', N'', 1, 30, N'', 0, '2023-01-01 00:01:01.001', NULL, 142307070910551, N'superAdmin', 0, NULL, '0');");
//            sql.AppendLine();
//            sql.AppendLine("-- 删除权限");
//            sql.Append("INSERT INTO [dbo].[sys_menu] ([Id], [Pid], [Pids], [Name], [Code], [Type], [Icon], [Router], [Component], [Permission], [Application], [OpenType], [Visible], [Link], [Redirect], [Weight], [Sort], [Remark], [Status], [CreateTime], [EditeTime], [CreatedUserId], [CreatedUserName], [EditorUserId], [EditorUserName], [Deleted]) ");
//            sql.Append("VALUES (" + IdGenerator.Id + ", " + Id + ", N'[" + rootId + "],[" + Id + "],', N'" + dbTableInfo.Description + "删除', N'" + urlName + "_delete', 2, N'', N'', N'', N'" + input.EntityName + ":delete', N'system', 0, N'Y', N'', N'', 1, 40, N'', 0, '2023-01-01 00:01:01.001', NULL, 142307070910551, N'superAdmin', 0, NULL, '0');");
//            sql.AppendLine();
//            sql.AppendLine("-- 查看权限");
//            sql.Append("INSERT INTO [dbo].[sys_menu] ([Id], [Pid], [Pids], [Name], [Code], [Type], [Icon], [Router], [Component], [Permission], [Application], [OpenType], [Visible], [Link], [Redirect], [Weight], [Sort], [Remark], [Status], [CreateTime], [EditeTime], [CreatedUserId], [CreatedUserName], [EditorUserId], [EditorUserName], [Deleted]) ");
//            sql.Append("VALUES (" + IdGenerator.Id + ", " + Id + ", N'[" + rootId + "],[" + Id + "],', N'" + dbTableInfo.Description + "查看', N'" + urlName + "_detail', 2, N'', N'', N'', N'" + input.EntityName + ":detail', N'system', 0, N'Y', N'', N'', 1, 50, N'', 0, '2023-01-01 00:01:01.001', NULL, 142307070910551, N'superAdmin', 0, NULL, '0');");
//            sql.AppendLine();

//            var targetPath = GetTargetPath(input, prifix: "", lastfix: "", "SQL", input.EntityName);
//            System.IO.File.WriteAllText(targetPath, sql.ToString(), System.Text.Encoding.UTF8);
//        }
//        /// <summary>
//        /// 获取模板文件路径集合
//        /// </summary>
//        /// <returns></returns>
//        private string GetTemplatePath(string tempName)
//        {
//            var templatePath = AppContext.BaseDirectory + @"wwwroot\Template\";
//            return Path.Combine(templatePath, tempName);
//        }

//        /// <summary>
//        /// 设置生成文件路径
//        /// </summary>
//        /// <param name="input"></param>
//        /// <param name="prifix"></param>
//        /// <param name="lastfix"></param>
//        /// <param name="path"></param>
//        /// <returns></returns>
//        private string GetTargetPath(CreateEntityInput input,string prifix  , string lastfix ,params string[] path)
//        {
//            string spath = "";

//            foreach (var t in path) {
//                spath+= t + "/";
//            }

//            spath = spath.Substring(0, spath.Length - 1);

//            var backendPath = Path.Combine(new DirectoryInfo(AppContext.BaseDirectory).Parent.FullName,"CodeGen", spath);
//            if (!Directory.Exists(backendPath))
//            {
//                Directory.CreateDirectory(backendPath);
//            }
//            var entityPath = Path.Combine(backendPath, prifix+input.EntityName + lastfix+".cs");
//            return entityPath;
//        }
//    }
//}
